<?php

namespace app\schoolwall\controller;

use think\Controller;

class User extends Controller
{
    protected $UserModel = null;
    protected $CodeModel = null;
    protected $RegionModel = null;
    protected $SchoolModel = null;
    protected $FollowModel = null;

    public function _initialize()
    {
        $this->UserModel = model('common/User/User');
        $this->CodeModel = model('common/User/Code');
        $this->RegionModel = model('common/Region');
        $this->SchoolModel = model('common/School/School');
        $this->FollowModel = model('common/User/Follow');
    }

    //密码登录
    public function login()
    {
        if ($this->request->isPost()) {
            $password = $this->request->param('password', '', 'trim');
            $username = $this->request->param('username', '', 'trim');

            if (!$username || !$password) {
                return $this->error('用户名或密码不能为空');
            }

            $user = $this->UserModel->whereOr([
                'email' => $username,
                'qq' => $username,
                'mobile' => $username,
            ])->with('school')->find();

            if (!$user) {
                return $this->error('用户不存在');
            }

            if ($user['password'] != md5($password . $user['salt'])) {
                return $this->error('密码错误');
            }

            $this->success('登录成功', null, $user);
            //$this->result( $user,0,'登录成功', 'json');//返回json数据
        }
    }

    //邮箱验证码登录
    public function codelogin()
    {
        if ($this->request->isPost()) {
            $email = $this->request->param('email', '', 'trim');
            $code = $this->request->param('code', '', 'trim');

            if (!$email || !$code) {
                return $this->error('邮箱或验证码不能为空');
            }

            $user = $this->UserModel->where('email', $email)->with('school')->find();
            if (!$user) {
                return $this->error('用户不存在');
            }

            $usercode = $this->CodeModel->where(['email' => $email, 'code' => $code])->find();
            if (!$usercode) {
                return $this->error('验证码错误');
            } else {
                $this->success('登录成功', null, $user);
            }
        }
    }

    //注册账号
    public function register()
    {
        if ($this->request->isPost()) {
            $username = $this->request->param('username', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $email = $this->request->param('email', '', 'trim');
            $code = $this->request->param('code', '', 'trim');
            $requstpassword = $this->request->param('requstpassword', '', 'trim');

            if ($password !== $requstpassword) {
                return $this->error('两次密码不一致');
            }

            $user = $this->UserModel->where('username', $username)->find();

            if ($user) {
                return $this->error($username . '该昵称已存在');
            }

            $usercode = $this->CodeModel->where(['email' => $email, 'code' => $code])->find();

            if (!$usercode) {
                return $this->error('验证码错误');
            }

            //生成随机盐
            $salt = build_randstr();

            //拼接生成密码
            $password = md5($password . $salt);

            $data = [
                'username' => $username,
                'password' => $password,
                'salt' => $salt,
                'email' => $email,
            ];

            $res = $this->UserModel->validate('common/Schoolwall/User.register')->save($data);

            if ($res) {
                return $this->success('注册成功', null);
            } else {
                return $this->error($this->UserModel->getError());
            }
        }
    }

    //验证登录，刷新登录凭证
    public function check()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', '', 'trim');
            $username = $this->request->param('email', '', 'trim');

            $user = $this->UserModel
                ->where('user.id', $id)
                ->whereOr([
                    'mobile' => $username,
                    'email' => $username,
                    'qq' => $username
                ])->with('school')->find();

            //添加关注的followid
            $followid = $this->FollowModel->where('userid', $id)->column('followid');
            if ($followid) {
                $user['followid'] = $followid;
            } else {
                $user['followid'] = [];
            }

            if ($user) {
                $this->success('登录成功', null, $user);
            } else {
                $this->error('登录失败');
            }
        }
    }

    //注销账号
    public function deleteuser()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', '', 'trim');
            $email = $this->request->param('email', '', 'trim');
            $code = $this->request->param('code', '', 'trim');

            if (!$id || !$email || !$code) {
                return $this->error('参数错误');
            }

            $user = $this->UserModel->where('id', $id)->find();

            if (!$user) {
                return $this->error('用户不存在');
            }

            $usercode = $this->CodeModel->where(['email' => $email, 'code' => $code])->find();

            if (!$usercode) {
                return $this->error('验证码错误');
            }

            $res = $this->UserModel->where(['id' => $id, 'email' => $email])->delete();

            if ($res) {
                return $this->success('注销成功');
            } else {
                return $this->error('注销失败');
            }
        }
    }

    //修改密码
    public function editpassword()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', '', 'trim');
            $requstpassword = $this->request->param('requstPassword', '', 'trim');
            $oldpassword = $this->request->param('oldPassword', '', 'trim');
            $newpassword = $this->request->param('newPassword', '', 'trim');
        }

        if ($requstpassword !== $newpassword) {
            return $this->error('两次密码不一致');
        }

        $user = $this->UserModel->where('id', $id)->find();

        if (!$user) {
            return $this->error('用户不存在');
        }

        if ($user['password'] !== md5($oldpassword . $user['salt'])) {
            return $this->error('旧密码错误');
        }

        $password = md5($newpassword . $user['salt']);

        $res = $this->UserModel->where('id', $id)->update(['password' => $password]);

        if ($res) {
            return $this->success('修改成功');
        } else {
            return $this->error('修改失败');
        }
    }

    //完善账号
    public function editid()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $qq = $this->request->param('qq', '', 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');

            $user = $this->UserModel->where('id', $id)->find();
            if (!$user) {
                return $this->error('用户不存在');
            }

            if ($user['password'] !== md5($password . $user['salt'])) {
                return $this->error('密码错误');
            }

            $qqinfo = $this->UserModel->where('qq', $qq)->find();
            if ($qqinfo) {
                return $this->error('该QQ号已被注册');
            }
            $mobileinfo = $this->UserModel->where('mobile', $mobile)->find();
            if ($mobileinfo) {
                return $this->error('该手机号已被注册');
            }

            $data = [
                'id' => $id,
                'qq' => $qq,
                'mobile' => $mobile
            ];

            $res = $this->UserModel->isUpdate(true)->save($data);

            if ($res) {
                return $this->success('修改成功');
            } else {
                return $this->error($this->UserModel->getError());
            }
        }
    }

    //更改邮箱
    public function editemail()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', '', 'trim');
            $email = $this->request->param('email', '', 'trim');
            $code = $this->request->param('code', '', 'trim');

            if (empty($email) || empty($code)) {
                return $this->error('邮箱和验证码均不能为空');
            }

            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                return $this->error('邮箱格式不正确');
            }

            $user = $this->UserModel->where('id', $id)->find();

            if (!$user) {
                return $this->error("用户不存在");
            }

            $useremail = $this->UserModel->where('email', $email)->find();
            if ($useremail) {
                return $this->error('该邮箱已被注册');
            }
        }
    }

    //更改个人资料
    public function editprofile()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $id = $this->request->param('id', '', 'trim');

            $user = $this->UserModel->where('id', $id)->find();

            if (!$user) {
                return $this->error("用户不存在");
            }

            //昵称验证
            if (!empty($params['username']) && $params['username'] !== $user['username']) {
                $copyusername = $this->UserModel->where('username', $params['username'])->find();

                if ($copyusername) {
                    $this->error('该昵称已存在');
                } else {
                    unset($params['username']);
                }
            }

            //学校认证
            if (!empty($params['schoolid']) && $params['schoolid'] !== $user['schoolid']) {
                $school = $this->SchoolModel->where('id', $params['schoolid'])->find();

                if (!$school) {
                    $this->error('该学校不存在');
                }
            } else {
                unset($params['schoolid']);
            }

            //性别认证
            if (!empty($params['gender']) && $params['gender'] !== $user['gender']) {
            } else {
                unset($params['gender']);
            }

            //地区认证
            if (!empty($params['region']) && $params['region'] !== $user['province'] && $params['region'] !== $user['city'] && $params['region'] !== $user['district']) {
                $city = $this->RegionModel->where('code', $params['region'])->value('parentpath');

                if (!$city) {
                    $this->error('地区不存在');
                }

                $path = explode(',', $city);
                $params['province'] = $path[0] ?? NULL; //接着给$params数组赋值,分别为省市区
                $params['city'] = $path[1] ?? NULL;
                $params['district'] = $path[2] ?? NULL;

                unset($params['region']);
            } else {
                unset($params['region']);
            }

            //生日认证
            if (!empty($params['birthday']) && $params['birthday'] !== $user['birthday']) {
            } else {
                unset($params['birthday']);
            }

            //头像认证
            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {

                $avatar = build_upload('avatar'); //调用build_upload方法,上传头像,对图片进行处理

                if ($avatar['code'] === 0) //code为返回的状态码,为0表示失败,
                {
                    $this->error($avatar['msg']); //抛出错误信息
                }

                $params['avatar'] = $avatar['data'];
            }

            $result = $this->UserModel->isUpdate(true)->save($params);

            if ($result === false) //如果返回false,就表示验证失败
            {
                if (isset($params['avatar']) && $_FILES['avatar']['size'] > 0) {
                    is_file('.' . $params['avatar']) && unlink('.' . $params['avatar']); //判断上传的文件是否存在,如果存在,就删除上传的文件
                }
                $this->error($this->UserModel->getError()); //抛出错误信息
            } else {
                if (isset($params['avatar']) && $_FILES['avatar']['size'] > 0) {
                    is_file('.' . $user['avatar']) && unlink('.' . $user['avatar']);
                }
                $this->success('更新基本资料成功');
            }
        }
    }

    //获取用户详细信息
    public function getuserinfo()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', '', 'trim');
            $userid = $this->request->param('userid', '', 'trim');

            $user = $this->UserModel->where('id', $id)->find();

            if (!$user) {
                return $this->error('用户不存在');
            }

            $userinfo = $this->UserModel->where('user.id', $userid)->with('school')->find();

            $followres = $this->FollowModel->where('userid', $id)->where('followid', $userid)->find();

            if ($followres) {
                $userinfo['is_follow'] = true;
            } else {
                $userinfo['is_follow'] = false;
            }

            if ($userinfo) {
                return $this->success('获取成功', null, $userinfo);
            } else {
                return $this->error('用户不存在');
            }
        }
    }

    // 关注
    public function follow()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', '', 'trim');
            $followid = $this->request->param('followid', '', 'trim');

            $user = $this->UserModel->find($userid);
            if (!$user) {
                return $this->error('用户不存在');
            }

            $follow = $this->UserModel->find($followid);
            if (!$follow) {
                return $this->error('关注用户不存在');
            }

            $followres = $this->FollowModel->where('userid', $userid)->where('followid', $followid)->find();
            if ($followres) {
                return $this->error('已关注');
            }

            $data = [
                'userid' => $userid,
                'followid' => $followid,
            ];

            $res = $this->FollowModel->save($data);

            if ($res) {
                return $this->success('关注成功');
            } else {
                return $this->error('关注失败');
            }
        }
    }

    // 取消关注
    public function unfollow()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', '', 'trim');
            $followid = $this->request->param('followid', '', 'trim');

            $user = $this->UserModel->where('id', $userid)->find();
            if (!$user) {
                return $this->error('用户不存在');
            }

            $follow = $this->UserModel->where('id', $followid)->find();
            if (!$follow) {
                return $this->error('关注用户不存在');
            }

            $followres = $this->FollowModel->where('userid', $userid)->where('followid', $followid)->find();

            if (!$followres) {
                return $this->error('未关注');
            }

            $res = $this->FollowModel->where('userid', $userid)->where('followid', $followid)->delete();

            if ($res) {
                return $this->success('取消关注成功');
            } else {
                return $this->error('取消关注失败');
            }
        }
    }

    // 获取关注列表
    public function getfollowlist()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', '', 'trim');

            $user = $this->UserModel->where('id', $userid)->find();

            if (!$user) {
                return $this->error('用户不存在');
            }

            $count = $this->FollowModel->where('userid', $userid)->count();
            $followlist = $this->FollowModel->where('userid', $userid)->with('user')->select();

            // 循环$item，判断是否关注过，是则在数组中添加is_follow字段
            foreach ($followlist as $key => $value) {
                $value['is_follow'] = true;
            }

            $data = [
                'count' => $count,
                'item' => $followlist,
            ];

            if ($followlist) {
                return $this->success('获取成功', null, $data);
            } else {
                return $this->error('获取失败');
            }
        }
    }

    //获取关注列表的followid
    public function getfollowlistuserid()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', '', 'trim');

            $user = $this->UserModel->where('id', $userid)->find();
            if (!$user) {
                return $this->error('用户不存在');
            }

            $followid = $this->FollowModel->where('userid', $userid)->column('followid');

            if ($followid) {
                return $this->success('获取成功', null, $followid);
            } else {
                return $this->error('暂未有关注的用户');
            }
        }
    }
}
